package com.znf.util;

import com.znf.config.CustomUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class CurrentUserUtil {
    /**
     * 获取当前用户
     *
     * @return
     */
    public static CustomUserDetails getCurrentUser() {
        // 从SecurityContextHolder获取当前的Authentication对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 如果用户未登录，authentication可能为null
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new IllegalStateException("User is not logged in");
        }
        // 从Authentication对象中获取UserDetails
        return (CustomUserDetails) authentication.getPrincipal();
    }
}

